from PySide6.QtWidgets import QWidget,QAbstractItemView,QMenu,QTableWidgetItem,QMessageBox,QDialog
from PySide6.QtCore import Qt,QDate
import pandas as pd
import datetime
import uuid
from sqlalchemy.orm import Session
from settings.publicvar import engine
from views.schoolInfo.model.SchoolInfo import SchoolInfo
from views.person.model.person import PersonBaseInfo,PersonType,SurePersonType
from views.bankinfo.model.bankinfo import BankCard
from views.initsetting.mode.initsetting import InitSetting
from views.initsetting.initsettingView import InitSettingView
from views.issuedmange.sureissuedperson.issuedmange import Ui_item
from views.issuedmange.model.issuedmange import IssuedPersonSure
from views.issuedmange.sureissuedperson.addissuedamount.addallamountView import AddAllAmountView
from views.issuedmange.sureissuedperson.savepersondataView import SavePersonDataView

class IssuedMangeView(QWidget,Ui_item):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # self.itemtable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.itemtable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.itemtable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.itemtable.customContextMenuRequested.connect(self.generate_menu)

        self.automenuData()
        self.surepersontypes = []
        self.sereachedit.editingFinished.connect(self.serearchnameFun)
        self.serearchbtn.clicked.connect(self.serearchFun)
        self.savebtn.clicked.connect(self.saveFun)


    # 导航数据加载
    def automenuData(self):
        with Session(engine) as session, session.begin():
            self.issueddate.setDate(QDate.currentDate())
            try:
                initseting = session.query(InitSetting).one()
                name = initseting.school.name
                if name == '寻甸回族彝族自治县柯渡镇中心学校':
                    schoolinfo = session.query(SchoolInfo).all()
                    names = [item.name for item in schoolinfo]
                    self.school.addItems(names)
                else:
                    self.school.addItem(name)
                self.school.setCurrentText(name)
                persontypes = session.query(PersonType).all()
                for item in persontypes:
                    self.persontype.addItem(item.persontype)
                self.persontype.setCurrentText('保育员')
            except:
                QMessageBox.critical(None,'失败','请在设置里初始化设置，才能操作！')
                InitSettingView().exec()

    # 表格加载数据
    def setTableStructure(self, data):
        self.itemtable.setRowCount(len(data))
        for i, item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.itemtable.setItem(i, 0, idx)
            school = QTableWidgetItem(item.school)
            self.itemtable.setItem(i,1,school)
            name = QTableWidgetItem(item.name)
            self.itemtable.setItem(i,2,name)
            IDcard = QTableWidgetItem(item.IDcard)
            self.itemtable.setItem(i,3,IDcard)
            bankName= QTableWidgetItem(item.bankName)
            self.itemtable.setItem(i,4,bankName)
            cardNumber= QTableWidgetItem(item.cardNumber)
            self.itemtable.setItem(i,5,cardNumber)
            openbank= QTableWidgetItem(item.openbank)
            self.itemtable.setItem(i,6,openbank)
            amount = QTableWidgetItem(item.amount)
            self.itemtable.setItem(i,7,amount)
            paymenttype = QTableWidgetItem(item.paymenttype)
            self.itemtable.setItem(i,8,paymenttype)
            persontype = QTableWidgetItem(item.persontype)
            self.itemtable.setItem(i,9,persontype)
            issueddate= QTableWidgetItem(item.issueddate.strftime("%Y年%m月%d日"))
            self.itemtable.setItem(i,10,issueddate)
            uniqueID = QTableWidgetItem(item.uniqueID)
            self.itemtable.setItem(i,12,uniqueID)
            mark = QTableWidgetItem(item.mark)
            self.itemtable.setItem(i, 13, mark)

    # 搜索数据
    def serearchnameFun(self):
        '''
        self.itemtable.setRowCount(0)

        sereachdata = self.sereachedit.text().strip()
        if sereachdata:
            with Session(engine) as session,session.begin():
                IDcarddata = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard == sereachdata).all()
                namedata = session.query(PersonBaseInfo).filter(PersonBaseInfo.name == sereachdata).all()
                iphonedata = session.query(PersonBaseInfo).filter(PersonBaseInfo.iphone == sereachdata).all()
                data = IDcarddata + namedata + iphonedata
                if data:
                    operation =  OperationView(data)
                    if operation.exec() == QDialog.Accepted:
                        self.surepersontypes = self.surepersontypes + operation.returndata
                        self.setTableStructure(self.surepersontypes)
                        self.showdata.setText('共%s条,请核实人员总数。 1.人员确定 2.保存数据 3.打印材料里下载数据' % (
                            len(self.surepersontypes)))
                else:
                    QMessageBox.critical(None,'失败','没有查询到数据，请重新查询！')
                    '''
        rows = self.itemtable.rowCount()
        columns = self.itemtable.columnCount()
        for i in range(rows):
            for j in range(columns):
                tem = self.itemtable.item(i,j)
                if tem == None or tem.text().strip() == '':
                    print('为空')
                else:
                    print(self.itemtable.item(i,j).text())


    # 搜索框数据处理
    def serearchFun(self):
        school = self.school.currentText()
        persontype = self.persontype.currentText()
        issuedtype = self.issuedtype.currentText()
        issueddate = self.issueddate.date()
        with Session(engine) as session,session.begin():
            surepersontype = session.query(SurePersonType).filter(SurePersonType.persontype.has(PersonType.persontype==persontype)).all()
            if not surepersontype:
                QMessageBox.critical(None,'数据出错','找不到人员信息，请先维护类型确定信息')
            else:
                issueddate = datetime.date(issueddate.year(),issueddate.month(),issueddate.day())
                tem =[]
                IDcards =[]
                for item in surepersontype:
                    IDcards.append(item.personinfo.IDcard)
                    uniqueID = str(uuid.uuid4()) + '-' + str(datetime.datetime.now())
                    tem.append({'school':school,'name':item.personinfo.name,'IDcard':item.personinfo.IDcard,'paymenttype':issuedtype,'persontype':persontype,'issueddate':issueddate,'uniqueID':uniqueID})
                bankcards = session.query(BankCard).filter(BankCard.IDNumber.in_(IDcards)).all()
                if len(bankcards) != len(tem):
                    QMessageBox.critical(None,'失败','银行卡信息查询不完整，请类型确定与银行卡信息保持一致！')
                else:
                    bankcards = [{'IDcard':item.IDNumber,'bankName':item.bankname,'cardNumber':item.cardnumber,'openbank':item.openbank} for item in bankcards]
                    surepersons = pd.DataFrame(tem)
                    bankcards = pd.DataFrame(bankcards)
                    surepersontypes = pd.merge(surepersons,bankcards,on='IDcard')
                    surepersontypes['mark'] = ''
                    surepersontypes = surepersontypes.to_dict('records')
                    surepersontypes = [IssuedPersonSure(**item) for item in surepersontypes]
                    self.showdata.setText('共%s条,请核实人员总数。 1.人员确定 2.保存数据 3.打印材料里下载数据' %(len(surepersontypes)))
                    self.setTableStructure(surepersontypes)
                    self.surepersontypes =surepersontypes

    # 保存数据
    def saveFun(self):
        issueddate = self.issueddate.date()
        issueddate = datetime.date(issueddate.year(),issueddate.month(),issueddate.day())
        rows = self.itemtable.rowCount()
        columns = self.itemtable.columnCount()
        surepersontypes = []
        for i in range(rows):
            item = []
            for j in range(columns):
                tem = self.itemtable.item(i, j)
                if tem is None or tem.text().strip() == '':
                    item.append('')
                else:
                    item.append(tem.text())
            surepersontypes.append(item)
        try:
            surepersontypes = [{'school':item[1],'name':item[2],'IDcard':item[3],'bankName':item[4],'cardNumber':item[5],'openbank':item[6],'amount':float(item[7]),
                            'paymenttype':item[8],'persontype':item[9],'issueddate':issueddate,'uniqueID':item[12],'mark':item[13]} for item in surepersontypes]
            surepersontypes = [IssuedPersonSure(**item) for item in surepersontypes]
            if surepersontypes:
                SavePersonDataView(surepersontypes).exec()
                self.itemtable.setRowCount(0)
            else:
                QMessageBox.critical(None, '', '表格中数据为空，不能存入数据库！')
        except:
            QMessageBox.critical(None,'','发放金额中没有金额或不是数据,请修改金额!')


    def saveDialogFun(self):
        with Session(engine) as session,session.begin():
            if self.surepersontypes:
                session.add_all(self.surepersontypes)
                QMessageBox.information(None,'成功','添加成功%s条！,请到打印数据处，下载数据！'%len(self.surepersontypes))
                self.itemtable.setRowCount(0)
            else:
                QMessageBox.critical(None,'','数据为空，不能存入数据库！')

    # 菜单数据
    def generate_menu(self,pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deletitem = menu.addAction('删除')
        addmonutitem = menu.addAction('添加发放金额')
        action = menu.exec(self.itemtable.mapToGlobal(pos))
        posrow = self.itemtable.currentRow()
        columns = self.itemtable.columnCount()

        if action == changeitem:
            pass
            # change = OperationPersonBaseInfo('change',data)
            # change.exec()
        elif action == deletitem:
            pass
            # delete = OperationPersonBaseInfo('delete',data)
            # delete.exec()
        elif action == viewitem:
            pass
            # view = OperationPersonBaseInfo('view',data)
            # view.exec()
        elif action == addmonutitem:
            addmount = AddAllAmountView()
            result = addmount.exec()
            if result == QDialog.Accepted:
                amount = addmount.amount
                issueddate = self.issueddate.date()
                issueddate = datetime.date(issueddate.year(), issueddate.month(), issueddate.day())
                rows = self.itemtable.rowCount()
                surepersontypes = []
                for i in range(rows):
                    item = []
                    for j in range(columns):
                        tem = self.itemtable.item(i, j)
                        if tem is None or tem.text().strip() == '':
                            item.append('')
                        else:
                            item.append(tem.text())
                    surepersontypes.append(item)
                surepersontypes = [{'school': item[1], 'name': item[2], 'IDcard': item[3], 'bankName': item[4],
                                        'cardNumber': item[5], 'openbank': item[6], 'amount': str(amount),
                                        'paymenttype': item[8], 'persontype': item[9], 'issueddate': issueddate,
                                        'uniqueID': item[12], 'mark': item[13]} for item in surepersontypes]
                surepersontypes = [IssuedPersonSure(**item) for item in surepersontypes]
                self.itemtable.setRowCount(0)
                self.setTableStructure(surepersontypes)